<template>
  <el-dialog
    :title="isEdit ? '编辑SOP' : '发布SOP'"
    v-model="dialogVisible"
    width="70%"
    :before-close="handleClose"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-input v-model="form.type" placeholder="请输入类型"></el-input>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <RichTextEditor v-model="form.content" />
      </el-form-item>

      <el-form-item label="附件">
        <el-upload
          class="upload-demo"
          :action="`${config.baseURL}/upload`"
          :headers="uploadHeaders"
          :auto-upload="true"
          :on-progress="handleUploadProgress"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          :show-file-list="false"
          name="file"
          method="post"
        >
          <el-button type="primary" :disabled="isUploading">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持任意格式文件</div>
          </template>
        </el-upload>

        <!-- 进度条 -->
        <el-progress 
          v-if="isUploading" 
          :percentage="uploadProgress"
          :status="uploadStatus"
        />

        <!-- 已上传文件显示区域 -->
        <div v-if="form.attachmentName" class="uploaded-file">
          <span class="file-name">
            <el-icon><Document /></el-icon>
            {{ form.attachmentName }}
          </span>
          <el-button type="primary" link @click="handleDownloadAttachment" :loading="downloading">
            下载
          </el-button>
          <el-button type="danger" link @click="handleDeleteFile">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :disabled="isUploading"
        >确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import RichTextEditor from './RichTextEditor.vue'
import axios from '../plugins/axios'
import { ElMessage } from 'element-plus'
import { Document, Delete } from '@element-plus/icons-vue'
import { config } from '../config'

const props = defineProps({
  visible: Boolean,
  editData: Object,
  isEdit: Boolean
})

const emit = defineEmits(['update:visible', 'onSubmit' ,'onClose'])

const dialogVisible = ref(false)
const formRef = ref(null)
const isUploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')
const downloading = ref(false)
const uploadHeaders = computed(() => {
  const headers = {
    'Content-Type': undefined
  }
  const token = localStorage.getItem('token')
  if (token) {
    headers.Authorization = token
  }
  return headers
})

const form = ref({
  title: '',
  type: '',
  content: '',
  attachment: '',
  attachmentName: ''
})

const canRequestSecureDownload = computed(() => {
  return !!(form.value.id && form.value.attachment && !form.value.attachment.startsWith('http'))
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

// 监听visible属性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
})

// 监听editData变化
watch(() => props.editData, (newVal) => {
  if (newVal) {
    form.value = { ...newVal }
  } else {
    form.value = {
      title: '',
      type: '',
      content: '',
      attachment: '',
      attachmentName: ''
    }
  }
}, { immediate: true })

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (valid) {
      const url = form.value.id ? '/lesson/update' : '/lesson/save'
      const response = await axios.post(url, form.value)
      
      if (response.data.code === 1) {
        ElMessage.success(form.value.id ? '编辑成功' : '发布成功')
        emit('onSubmit')
        dialogVisible.value = false
      } else {
        ElMessage.error(response.data.msg || '操作失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 文件上传相关方法
const beforeUpload = (file) => {
  isUploading.value = true
  uploadProgress.value = 0
  uploadStatus.value = ''
  return true
}

const handleUploadProgress = (event) => {
  uploadProgress.value = Math.round(event.percent)
}

const handleUploadSuccess = (response) => {
  isUploading.value = false
  uploadProgress.value = 100
  uploadStatus.value = 'success'
  
  if (response.code === 1) {
    form.value.attachment = response.data.filePath
    form.value.attachmentName = response.data.fileName
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error(response.msg || '文件上传失败')
  }
}

const handleUploadError = () => {
  isUploading.value = false
  uploadStatus.value = 'exception'
  uploadProgress.value = 0
  ElMessage.error('文件上传失败')
}

const handleDeleteFile = async () => {
  try {
    const response = await axios.delete(`/file/delete/${form.value.attachment}`)
    if (response.data.code === 1) {
      form.value.attachment = ''
      form.value.attachmentName = ''
      ElMessage.success('文件删除成功')
    } else {
      ElMessage.error(response.data.msg || '文件删除失败')
    }
  } catch (error) {
    console.error('删除文件失败:', error)
    ElMessage.error('删除文件失败')
  }
}

const handleDownloadAttachment = async () => {
  if (!form.value.attachment) return

  if (!canRequestSecureDownload.value) {
    window.open(form.value.attachment, '_blank')
    return
  }

  try {
    downloading.value = true
    const response = await axios.post(`/lesson/${form.value.id}/download-token`, null, { suppressErrorToast: true })
    if (response.data.code === 1) {
      const { token } = response.data.data
      const url = `${config.baseURL}/lesson/download/${token}`
      window.open(url, '_blank')
    } else {
      ElMessage.error(response.data.msg || '获取下载令牌失败')
    }
  } catch (error) {
    console.error('下载失败', error)
    ElMessage.error('下载失败，请稍后再试')
  } finally {
    downloading.value = false
  }
}

const handleClose = () => {
  emit('onClose')
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-select) {
  width: 100%;
}

.uploaded-file {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.uploaded-file .file-name {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

:deep(.el-progress) {
  margin-top: 10px;
  width: 99%;
}
</style> 
